<template>
  <div class="chat-container">
    <div class="chat-header">
      <h2>AI客服助手</h2>
      <button @click="startNewSession" class="new-session-button">开启新对话</button>
    </div>

    <div class="chat-messages">
      <div v-for="(message, index) in messages" :key="index" :class="['message', message.role]">
        <div class="message-role">{{ message.role === 'user' ? '您' : 'AI助手' }}</div>
        <div class="message-content" v-html="formatMessageContent(message.content)"></div>
      </div>

      <div v-if="loading" class="loading-message">
        <div class="message-role">AI助手</div>
        <div class="message-content typing-indicator">
          <span></span><span></span><span></span>
        </div>
      </div>
    </div>

    <div class="chat-input-area">
      <div v-if="error" class="error-message">{{ error }}</div>
      <div class="input-group">
        <input
            v-model="inputMessage"
            @keyup.enter="sendMessage"
            placeholder="请输入您的问题..."
            :disabled="loading"
        />
        <BaiDuVoiceRecognition @recognized="onVoiceRecognized" />
        <button @click="sendMessage" :disabled="loading || !inputMessage.trim()">
          {{ loading ? '发送中...' : '发送' }}
        </button>
      </div>
      <button v-if="loading" @click="cancelRequest" class="cancel-button">
        取消请求
      </button>
    </div>
  </div>
</template>

<script>
import BaiDuVoiceRecognition from "../components/BaiDuVoiceRecognition.vue";
export default {
  components: {
    BaiDuVoiceRecognition,
  },
  data() {
    return {
      messages: [],
      inputMessage: '',
      loading: false,
      error: null,
      eventSource: null,
      sessionId: null // 新增sessionId存储
    }
  },
  methods: {
    formatMessageContent(content) {
      // 1. 先处理大分段标记
      let formatted = content
          .replace(/\*\*1/g, '<div class="section-break"></div>1')
          .replace(/###+/g, '<div class="section-break"></div>')
          .replace(/---###+/g, '<div class="section-break"></div>');


      // 2. 处理加粗文本（标蓝）
      formatted = formatted
          .replace(/\*\*([^*]+)\*\*/g, '<span class="highlight-blue">$1</span>');

      // 3. 改进的 - 换行处理（关键修复）
      formatted = formatted
          // 处理行首的 -
          .replace(/(^|\n)-\s*([^\n]*)/g, '$1<div class="line-break">• $2</div>')
          // 处理行中的 -（确保后面有空格）
          .replace(/([^\n])-\s/g, '$1<div class="line-break">• ')
          // 普通换行
          .replace(/\n/g, '<br>');

      return formatted;
    },
    sendMessage() {
      if (!this.inputMessage.trim() || this.loading) return;

      this.messages.push({
        role: 'user',
        content: this.inputMessage
      });

      const aiMessageIndex = this.messages.push({
        role: 'assistant',
        content: ''
      }) - 1;

      this.loading = true;
      this.error = null;
      const userInput = this.inputMessage;
      this.inputMessage = '';

      // 构建请求URL
      let url = `http://localhost:9998/ai-customerservice/chat-stream?input=${encodeURIComponent(userInput)}`;
      if (this.sessionId) {
        url += `&sessionId=${encodeURIComponent(this.sessionId)}`;
      }

      this.eventSource = new EventSource(url);
      console.log("Session ID:", this.sessionId)
      this.eventSource.onmessage = (event) => {
        // 确保获取并保存sessionId
        if (event.lastEventId) {
          this.sessionId = event.lastEventId;

          localStorage.setItem('ai_sessionId', this.sessionId); // 持久化存储
        }

        const chunk = event.data.replace(/\*\*/g, '**\u200B');
        this.messages[aiMessageIndex].content += chunk;
        this.scrollToBottom();
      };

      this.eventSource.onerror = () => {
        if (this.messages[aiMessageIndex].content === '') {
          this.messages[aiMessageIndex].content = '抱歉，回答生成失败';
        }
        this.loading = false;
        this.eventSource.close();
      };
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$el.querySelector('.chat-messages');
        if (container) {
          container.scrollTop = container.scrollHeight;
        }
      });
    },
    cancelRequest() {
      if (this.eventSource) {
        this.eventSource.close();
        this.loading = false;
        const lastMessage = this.messages[this.messages.length - 1];
        if (lastMessage.role === 'assistant') {
          lastMessage.content += ' (已取消)';
        }
      }
    },
    onVoiceRecognized(text) {
      this.inputMessage = text; // 将识别结果填入输入框
      // 不自动发送，让用户自己点击发送按钮
    },
    startNewSession() {
      // 清空消息记录
      this.messages = [];

      // 清空当前的 sessionId
      this.sessionId = null;

      // 从本地存储中移除旧的 sessionId
      localStorage.removeItem('ai_sessionId');

      // 可选：自动发送欢迎消息或提示
      this.messages.push({ role: 'assistant', content: '您好，我是AI助手，请问有什么可以帮您？' });
    }
  },
  created() {
    // 从本地存储恢复sessionId
    this.sessionId = localStorage.getItem('ai_sessionId');
    // 自动发送欢迎消息
    this.messages.push({
      role: 'assistant',
      content: '您好，我是AI助手，请问有什么可以帮您？'
    });
  },
  beforeDestroy() {
    if (this.eventSource) {
      this.eventSource.close();
    }
  },
}
</script>

<style>
.chat-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #e0e0e0;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  background-color: #fff;
}

.chat-header {
  text-align: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
  position: relative; /* 添加这行 */
}
.new-session-button {
  position: absolute;
  top: 10px;
  right: 20px;
  padding: 6px 12px;
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}
.chat-header h2 {
  margin: 0;
  color: #1976d2;
}

.chat-messages {
  height: 500px;
  overflow-y: auto;
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fafafa;
  border-radius: 8px;
}

.message {
  margin-bottom: 15px;
  padding: 12px;
  border-radius: 8px;
  max-width: 80%;
}

.message.user {
  background-color: #e3f2fd;
  margin-left: auto;
  border-bottom-right-radius: 4px;
}

.message.assistant {
  background-color: #f5f5f5;
  margin-right: auto;
  border-bottom-left-radius: 4px;
}

.message-role {
  font-weight: bold;
  font-size: 0.8em;
  margin-bottom: 5px;
  color: #555;
}

.message-content {
  white-space: pre-wrap;
  word-wrap: break-word;
  line-height: 1.6;
}

.highlight-blue {
  color: #1890ff;
  font-weight: bold;
}

.section-break {
  height: 1px;
  background-color: #e8e8e8;
  margin: 1em 0;
}

.section-title {
  font-weight: bold;
  margin: 1em 0 0.5em;
  color: #333;
}

.message-content br + br {
  display: block;
  content: "";
  margin-bottom: 0.5em;
}

.loading-message {
  margin-bottom: 15px;
  padding: 12px;
  border-radius: 8px;
  background-color: #f5f5f5;
  margin-right: auto;
  border-bottom-left-radius: 4px;
  max-width: 80%;
}

.typing-indicator {
  display: flex;
  align-items: center;
  height: 17px;
}

.typing-indicator span {
  height: 8px;
  width: 8px;
  background-color: #666;
  border-radius: 50%;
  display: inline-block;
  margin: 0 2px;
  animation: typing 1s infinite ease-in-out;
}

@keyframes typing {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-5px);
  }
}

.chat-input-area {
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.input-group {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

.input-group input {
  flex: 1;
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
}

.input-group button {
  padding: 10px 20px;
  background-color: #1976d2;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.input-group button:disabled {
  background-color: #90caf9;
  cursor: not-allowed;
}

.cancel-button {
  padding: 8px 15px;
  background-color: #f44336;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.error-message {
  color: #d32f2f;
  margin-bottom: 10px;
  font-size: 14px;
}
.highlight-blue {
  color: #1890ff !important;  /* 使用!important确保覆盖其他样式 */
  font-weight: bold;
  display: inline;            /* 防止变成块级元素 */
}

/* 新增列表项样式 */
.line-break {
  margin: 0.5em 0;
  padding-left: 1em;
  position: relative;
  display: block;
}

.line-break::before {
  content: "•";
  position: absolute;
  left: 0;
  color: #666;
}

</style>